package com.example.service;

import com.example.latch.EtcdLeaderLatch;
import com.example.latch.EtcdLeaderLatchListener;
import io.etcd.jetcd.Watch;
import io.etcd.jetcd.watch.WatchEvent;
import io.etcd.jetcd.watch.WatchResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;
import java.util.List;

@Service
public class SysEtcdMasterServiceImpl implements InitializingBean, DisposableBean, EtcdLeaderLatchListener, KeyListener {

    Logger logger = LoggerFactory.getLogger(getClass());

    @Resource
    private SysServerService sysServerService;

    @Resource
    private EtcdService etcdService;

    private EtcdLeaderLatch etcdLatch;

    private Watch.Watcher watcher;

    @Override
    public void afterPropertiesSet() throws Exception {
        this.etcdLatch = new EtcdLeaderLatch(etcdService.getClient(), "server", sysServerService.getServerKey(), 1, this);
        this.etcdLatch.start();
    }

    @Override
    public void destroy() throws Exception {
        this.etcdLatch.stop();
        this.watcher.close();
    }

    @Override
    public void isLeader() {
        logger.warn(sysServerService.getServerKey() + " is master server ....");
        this.watcher = this.etcdService.watchPrefKey("/yyyyy/", this);
    }

    @Override
    public void onNext(WatchResponse response) {
        List<WatchEvent> events = response.getEvents();
        for (WatchEvent event : events) {
            if (event.getEventType() == WatchEvent.EventType.DELETE) {
                logger.warn("eventType：" + event.getEventType() + " key: " + new String(event.getKeyValue().getKey().getBytes(), StandardCharsets.UTF_8));
            }
            if (event.getEventType() == WatchEvent.EventType.PUT) {
                logger.warn("eventType：" + event.getEventType() + " key: " + new String(event.getKeyValue().getKey().getBytes(), StandardCharsets.UTF_8));
            }
        }
    }
}
